'use strict'

import {
    app,
    protocol,
    BrowserWindow,
    Menu,
    Tray,
    globalShortcut,
    ipcMain
} from 'electron'
import {
    createProtocol
} from 'vue-cli-plugin-electron-builder/lib'
import installExtension, {
    VUEJS_DEVTOOLS
} from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
let path= require('path');
/*隐藏electron创听的菜单栏*/
Menu.setApplicationMenu(null)
// 托盘对象
var appTray = null    

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{
    scheme: 'app',
    privileges: {
        secure: true,
        standard: true
    }
}])

async function createWindow() {
    // Create the browser window.
    let win = null;
    win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {

            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            // process.env.ELECTRON_NODE_INTEGRATION
            nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
            contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
        },
        icon: path.join(__dirname, './tool.ico')
    })


    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        // win.loadURL('app://./index.html');
        win.loadURL(path.join(__dirname, './index.html'));
        
    }
    //进入软件即开启全屏
    win.setFullScreen(true);
    //配置ESC键退出全屏
    globalShortcut.register('ESC', () => {
        win.setFullScreen(false);
    })

    // 主进程缩小窗口
    ipcMain.on('window-min',function(){ // 收到渲染进程的窗口最小化操作的通知，并调用窗口最小化函数，执行该操作
        win.minimize();
    }) 
    
    // 手动打开开发者工具
    ipcMain.on('open-dev',function(){ // 收到渲染进程的窗口最小化操作的通知，并调用窗口最小化函数，执行该操作
        win.webContents.openDevTools({mode:'bottom'})
    }) 

    win.on('closed', () => {
        win = null;
    });

    
    // 设置托盘
    // Exit cleanly on request from parent process in development mode.
   
        if (process.platform === 'win32') {
            /* process.on('message', (data) => {
                if (data === 'graceful-exit') {
                    app.quit()
                }
            }) */

            
            // 系统托盘右键菜单
            var trayMenuTemplate = [
                {
                    label: '显示',
                    click: function() {
                        !win.isVisible() ? win.show() : null
                    }
                },
                /* {
                    label: '配置',
                    click: function() {
                        //app.quit()
                        let child = null;
                        child = new BrowserWindow({ 
                            parent: win,
                            width: 500,
                            height: 500,
                            webPreferences: {
                                nodeIntegration: true
                            }
                        })
                        let htmlUrl = path.join(__dirname, './child.html');
                        child.loadURL(htmlUrl);                    
                        child.on('closed', () => {
                            child = null;
                        });
                    }
                }, */
                {
                    label: '退出',
                    click: function() {
                        // ipc.send('close-main-window');
                        app.quit()
                    }
                }
            ]

            // 系统托盘图标目录 path.join(__static, './logo_1.ico')
            let trayIcon = path.join(__dirname, './tool.ico')
        
            appTray = new Tray(trayIcon)
        
            // 图标的上下文菜单
            const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
        
            // 设置此托盘图标的悬停提示内容
            appTray.setToolTip('工器具管理系统')
        
            // 设置此图标的上下文菜单
            appTray.setContextMenu(contextMenu)
            
            // 双击托盘显示隐藏
            appTray.on('double-click', () => {  win.isVisible() ? win.hide() : win.show()})

        } else {
            process.on('SIGTERM', () => {
                app.quit()
            })
        }
    

}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
app.commandLine.appendSwitch('--ignore-certificate-errors', 'true')
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            // await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
            console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    createWindow()
})

